<template>
  <web-view
    v-if="webViewSrc"
    :src="webViewSrc"
    @message="getMessage"
  />
</template>
<script>
import { getBaseGeocodingCommunalBase } from '@/api/address'
export default {
  data() {
    return {
      webViewSrc: ''
    }
  },
  onLoad(options) {
    this.webViewSrc = options?.domain + '/h5/applet-h5/html/map/map.html?versioion=20221228v1'
  },
  //#ifdef H5
  onShow() {
    // window.addEventListener('message', this.receiveMsg, true)
    window.onmessage = this.receiveMsg
  },
  // #endif
  methods: {
    //#ifdef H5
    receiveMsg(e) {
      console.log(e.data, 'abc')
      if (e.data.point) {
        this.getAddressDetails(e.data)
      }
    },
    // #endif
    getMessage(res) {
      console.log('接收到的消息：' + JSON.stringify(res.detail.data));
      const length = res.detail?.data.length
      const details = res.detail?.data[length - 1].location
      this.getAddressDetails(details)
    },
    // 获取地址详情
    async getAddressDetails(details) {
      const { point, address: detailAddress } = details
      const res = await getBaseGeocodingCommunalBase(point)
      if (res.errorCode == 0) {
        const cityInfo = this.getCityInfo(res.data)
        const address = `${cityInfo?.provinceName} ${cityInfo?.cityName} ${cityInfo?.areaName} ${cityInfo?.streetName}`
        this.navigateBackPage({
          cityInfo,
          'userInfo.address': address,
          'userInfo.detailAddress': detailAddress
        })
      } else {
        this.$u.toast(res.msg)
      }
    },
    // 获取cityInfo
    getCityInfo(details) {
      const cityInfo = {
        provinceId: details.provinceId,
        provinceName: details.provinceName,
        provinceCode: details.provinceCode,
        cityName: details.cityName,
        cityCode: details.cityCode,
        cityId: details.cityId,
        districtCode: details.districtCode,
        districtId: details.districtId,
        areaName: details.districtName,
        streetId: details.townId,
        streetName: details.townName,
        streetCode: details.townCode
      }
      return cityInfo
    },
    // 返回上一页
    navigateBackPage(params) {
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 1]
      for (const paramsKey in params) {
        if ((/\./g).test(paramsKey)) {
          const keys = paramsKey.split('.')
          if (keys.length == 2) {
            const [key1, key2] = keys
            prevPage.$vm[key1][key2] = params[paramsKey]
          } else if (keys.length == 3) {
            const [key1, key2, key3] = keys
            prevPage.$vm[key1][key2][key3] = params[paramsKey]
          }
        } else {
          prevPage.$vm[paramsKey] = params[paramsKey]
        }
      }
    }
  }
}
</script>
